package com.st.util;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.Part;

import org.apache.commons.io.IOUtils;
import org.springframework.web.multipart.MultipartFile;

public class UploadUtil {
	/**
	 * 支持MultipartFile的文件上传
	 */
	public static String saveFile(MultipartFile file, HttpServletRequest request, String path) {
		FileOutputStream fos = null;

		try {
			InputStream in = file.getInputStream();

			// 文件存放的路径
			path = request.getServletContext().getRealPath(path);

			// 随机文件名
			String fileName = UUID.randomUUID().toString();

			// 文件后缀名
			String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
			// 组合文件名
			fileName = fileName + suffix;

			fos = new FileOutputStream(path + "/" + fileName);

			IOUtils.copy(in, fos);
			return fileName;

		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null)
					fos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return null;
	}

	public static String saveFile(HttpServletRequest request, String name, String path) {

		FileOutputStream fos = null;

		try {
			Part part = request.getPart(name);

			// 字节输入流
			InputStream is = part.getInputStream();

			path = request.getServletContext().getRealPath(path);

			// 文件名的
			String fileName = UUID.randomUUID().toString();

			// 文件的后缀
			String suffix = part.getSubmittedFileName().substring(part.getSubmittedFileName().lastIndexOf("."));

			// 组合文件名
			fileName = fileName + suffix;

			// 写入到服务器的硬盘上
			fos = new FileOutputStream(path + "/" + fileName);

			byte[] buff = new byte[1024];
			while (true) {
				int length = is.read(buff);

				if (length < 0) {
					break;
				}

				fos.write(buff, 0, length);
			}

			fos.flush();

			return fileName;

		} catch (IOException e) {
			e.printStackTrace();
		} catch (ServletException e) {
			e.printStackTrace();
		} finally {
			try {
				if (fos != null)
					fos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		return null;
	}
}
